using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/**
 * Basically just a wrapper around a dictionary to hold all the global refs
 * TODO: This should be a singleton
 */
public class GlobalIndex : MonoBehaviour {
	public const string GLOBAL_INDEX_COMPONENT_NAME = "GlobalIndex";
	private Dictionary<string, Component> NameComponents = null;
	private Dictionary<System.Type, Component> TypeComponents = null;
	private GameObject g;
	
	private void InitGlobal() {
		this.g = GameObject.Find (GlobalAccess.GAMEOBJECT_NAME);
	}
	
	void Awake () {
		this.NameComponents = new Dictionary<string, Component>();
		this.TypeComponents = new Dictionary<System.Type, Component>();
	}
	
	void Start() {
		this.InitGlobal();
	}
	
	private bool CheckGetGlobalInitialized() {
		if (this.g == null) {
			this.InitGlobal ();
		}
		
		if (this.NameComponents == null) {
			this.NameComponents = new Dictionary<string, Component>();
		}
		
		if (this.TypeComponents == null) {
			this.TypeComponents = new Dictionary<System.Type, Component>();
		}
		
		if ((this.g == null) ||
			(this.NameComponents == null) ||
			(this.TypeComponents == null)) {
			return false;
		}
		
		return true;
	}
	
	public Component GetGlobalComponent(System.Type t) {
		Component c;
		if (!this.CheckGetGlobalInitialized()) {
			return null;
		}
		
		if (this.TypeComponents.ContainsKey (t)) {
			c = this.TypeComponents[t];
		} else {
			c = this.g.GetComponent (t);
			if (c != null) {
				/* memoize...kind of assume there's no deletion */
				if (!this.NameComponents.ContainsKey (c.name)) {
					this.NameComponents.Add (c.name, c);
				}
				this.TypeComponents.Add (t, c);
			}
		}
		
		return c;
	}
	
	public Component GetGlobalComponent(string comp_name) {		
		Component c = null;
		
		if (!this.CheckGetGlobalInitialized()) {
			return null;
		}
		
		if (this.NameComponents.ContainsKey (comp_name)) {
			c = this.NameComponents[comp_name];
		} else {
			c = this.g.GetComponent (comp_name);
			if (c != null) {
				/* memoize...kind of assume there's no deletion */
				this.NameComponents.Add (comp_name, c);
				if (!this.TypeComponents.ContainsKey(c.GetType())) {
					this.TypeComponents.Add (c.GetType (), c);
				}
			}
		}
		
		return c;
	}
}
